//
//  DietPlanViewController.m
//  KeepFit
//
//  Created by Fuzzie Liu on 15/10/28.
//  Copyright © 2015年 Fuzzie Liu. All rights reserved.
//

#import "DietPlanViewController.h"
#import "FLCalendar.h"
#import "NSDate+FLCalendar.h"
#import "DietPlanTableViewCell.h"
#import "DietPlanHeaderView.h"
#import "AddPlanViewController.h"
#import "BaseNavigationController.h"
#import "DietPlan.h"
#import "NSString+FromNSDate.h"
#import "DietPlanTableViewCell.h"

#define DietPlanCellReuse @"DietPlanCellReuse"
#define DietPlanHeaderReuse @"DietPlanHeaderReuse"

@interface DietPlanViewController ()<FLCalendarDelegate, AddPlanViewControllerDelegate>

@property (nonatomic, strong) FMDatabase *fmDB;
@property (nonatomic, strong) NSMutableArray *sourceArray;
//@property (nonatomic, strong) FLCalendar *calendar;
@property (nonatomic, strong) NSDate *date;

@end

@implementation DietPlanViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    FLCalendar *calendar = [[FLCalendar alloc] initWithDate:[NSDate date]];
    calendar.delegate = self;
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height) style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.tableView registerClass:[DietPlanTableViewCell class] forCellReuseIdentifier:DietPlanCellReuse];
    [self.tableView registerClass:[DietPlanHeaderView class] forHeaderFooterViewReuseIdentifier:DietPlanHeaderReuse];
    [self.view addSubview:_tableView];
    
    self.tableView.tableHeaderView = calendar;
    self.tableView.bounces = NO;
    
    [self creatFMDB];
    
}

- (void)calendarItemSelectedAtDate:(NSDate *)date
{
    
    self.date = date;
    [self getDataForDate];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.sourceArray.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 40;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    DietPlanTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:DietPlanCellReuse forIndexPath:indexPath];
    DietPlan *dietPlan = [self.sourceArray objectAtIndex:indexPath.row];
    cell.timeLabel.text = [dietPlan.date stringForDate];
    cell.contentLabel.text = dietPlan.content;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    NSDate *data = [NSDate date];
    NSDate *earlier = [data earlierDate:dietPlan.date];
    if ([earlier isEqualToDate:dietPlan.date]) {
        cell.tuImageView.image = [UIImage imageNamed:@"zhong.png"];
    }else
    {
        cell.tuImageView.image = [UIImage imageNamed:@"qing.png"];
    }
    return cell;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    DietPlanHeaderView *headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:DietPlanHeaderReuse];
    [headerView.addButton addTarget:self action:@selector(addPlanAction) forControlEvents:UIControlEventTouchUpInside];
    return headerView;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60;
}
- (void)addPlanAction
{
    AddPlanViewController *addPlanVC = [[AddPlanViewController alloc] init];
    addPlanVC.view.backgroundColor = [UIColor whiteColor];
    addPlanVC.delegate = self;
    BaseNavigationController *addNavi = [[BaseNavigationController alloc] initWithRootViewController:addPlanVC];
    [self presentViewController:addNavi animated:YES completion:^{
        NSLog(@"present add plan ViewController");
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark ---数据库---
- (void)creatFMDB
{
    //1.获得数据库文件的路径
    NSString *doc=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *fileName=[doc stringByAppendingPathComponent:@"KeepFit.sqlite"];
    
    //2.获得数据库
    self.fmDB =[FMDatabase databaseWithPath:fileName];
    
    //3.打开数据库
    if ([self.fmDB open]) {
        //4.创表
        BOOL result=[self.fmDB executeUpdate:@"CREATE TABLE IF NOT EXISTS t_dietplan (id integer PRIMARY KEY AUTOINCREMENT, content text NOT NULL, date text NOT NULL);"];
        if (result) {
            NSLog(@"创表成功");
        }else{
            NSLog(@"创表失败");
        }
    }
    NSLog(@"%@", fileName);
}
#pragma mark ---添加计划的代理方法---
- (void)addDietPlanWithDietPlan:(DietPlan *)dietPlan
{
    NSString *dateString = [dietPlan.date stringForDate];
    NSLog(@"%@, %@", dateString, dietPlan.content);
    BOOL result = [self.fmDB executeUpdate:@"INSERT INTO t_dietplan (content, date) VALUES(?,?);", dietPlan.content, dateString];
    if (result) {
        NSLog(@"添加成功");
    }else{
        NSLog(@"添加失败");
    }
}
#pragma mark ---选择日期后获取当日的计划---
- (void)getDataForDate
{
    self.sourceArray = [NSMutableArray array];
    FMResultSet *resultSet = [self.fmDB executeQuery:@"SELECT * FROM t_dietplan"];
    // 查找数据库
    while (resultSet.next) {
        // 根据查找结果创建出DietPlan对象
        DietPlan *newDP = [[DietPlan alloc] init];
        newDP.content = [resultSet stringForColumn:@"content"];
        NSString *dateString = [resultSet stringForColumn:@"date"];
        newDP.date = [dateString dateFromString];
        NSLog(@"content======%@, date======%@", newDP.content, newDP.date);
        NSDateComponents *components = [newDP.date dateComponentsForYMD];
//        NSLog(@"plan component=====%@", components);
        NSDateComponents *calendarComp = [self.date dateComponentsForYMD];
//        NSLog(@"calendar component======%@", calendarComp);
        // 当计划日期与选定日期相同时, 加入数据源数组
        if ([components isEqual:calendarComp]) {
            [self.sourceArray addObject:newDP];
        }
    }
    NSLog(@"plan======%ld", self.sourceArray.count);
    [self.tableView reloadData];
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        
        DietPlan *plan = [self.sourceArray objectAtIndex:indexPath.row];
        [self.fmDB executeUpdate:@"delete from t_dietplan where content = ?;",plan.content];
        [self.sourceArray removeObjectAtIndex:indexPath.row];
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationLeft];
    }
    [self.tableView reloadData];
}


@end
